package com.longshine.plc.net;

import com.longshine.plc.data.DataSource;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class ServerService
{
  private ServerSocket ss;
  private List<UpperMonitorClient> clients = new ArrayList();
  private DataSource source;

  public ServerService(DataSource source)
  {
    this.source = source;
  }
  public void startServer(int port) throws Exception {
    this.ss = new ServerSocket(port);
    while (this.ss != null) {
      Socket s = this.ss.accept();
      Thread.sleep(500L);
      UpperMonitorClient client = new UpperMonitorClient(s, this.source, this);
      this.clients.add(client);
      client.work();
    }
  }

  public void removerClient(UpperMonitorClient c) {
    this.clients.remove(c);
  }

  public void stopServer() {
    if (this.ss == null) {
      return;
    }
    for (UpperMonitorClient uc : this.clients) {
      uc.stopConn();
    }
    this.clients.clear();
    if (this.ss != null)
      try {
        this.ss.close();
        this.ss = null;
      }
      catch (IOException localIOException)
      {
      }
  }
}